#pragma once
#include "uart/ProtocolSender.h"
#include "water/typedef.h"
#include "logic_utility.hpp"
#include "base/time.hpp"
#include "water/timer_event.h"
#include "manager/hardware.h"
#include <cstring>


//制冰机命令
Inquiry_A2 Cur_a2;
struct WarnTab{
	std::string Warn;
	LayoutPosition p;
	std::string Warn1;
	bool IsShow;
};
#define NumberWarn 21
WarnTab warnTab[]{
		"缺水，请打开水源开关",{0,43,660,84},"",false,
		"进水测温度故障",{0,43,660,84},"",false,
		"进水水温过低",{0,43,660,84},"",false,
		"出水测温度故障",{0,43,660,84},"",false,
		"电压传感器故障(H2)",{0,43,660,84},"",false,
		"发热膜回路故障",{0,43,660,84},"",false,
		"超高温(H4)",{0,43,660,84},"",false,
		"过零电路故障(E7)",{0,43,660,84},"",false,
		"通讯故障",{0,43,660,84},"",false,
		"漏水故障",{0,43,660,84},"",false,
		"热水水泵开路故障(Eb)",{0,43,660,84},"",false,
};

static void set_timer_event_window_visible(int event_id, bool visible){
    LOCK_SCREEN->set_auto_count(true);
	if(event_id == E_TIMER_EVENT_ICE_ADD_WATER){
		mTimeIceWaterWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_FILTER_BRASH){
		mWashWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_DRAIN_WATER_SHORT){
		mDrainageWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_DRAIN_WATER_LONG){
		mDrainageWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_ALL_BRASH){
		mWashWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_MAKE_WATER_TIMEOUT){
		mOutTimeWndPtr->setVisible(visible);
	}else if(event_id == E_TIMER_EVENT_ICE_ADD_BLOCK){
		mTimeIceWndPtr->setVisible(visible);
        if (water::is_timer_event_running(E_TIMER_EVENT_ICE_ADD_BLOCK)) {
            water::stop_timer_event(E_TIMER_EVENT_ICE_ADD_BLOCK);
        }
	}
	if(visible) {
		EASYUICONTEXT->showNaviBar();
	}else {
		EASYUICONTEXT->hideNaviBar();
	}
}

void operateBrash(bool on) {
	if(on) {
 		if (water::get_water_state() != E_WATER_STATE_IDLE) {
			stop_water(true);
		}
		if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_FILTER_BRASH)) {
			return ;
		}
		LOCK_SCREEN->set_auto_count(false);
		water::start_timer_event(E_TIMER_EVENT_FILTER_BRASH);
	}else {
		water::stop_timer_event(E_TIMER_EVENT_FILTER_BRASH);
		water::stop_timer_event(E_TIMER_EVENT_ALL_BRASH);
		mWashWndPtr->setVisible(false);
		EASYUICONTEXT->hideNaviBar();
		LOCK_SCREEN->set_auto_count(true);
	}
}


void operateEmptyDevice(bool on) {
	if(on) {
		if(water::get_water_state() != E_WATER_STATE_IDLE) {
			stop_water(true);
		}
		protocol::setCold220V(false, false);//排水关闭制冷
		if(!is_can_start_auto_timer(E_TIMER_EVENT_ID_DRAIN_WATER_SHORT)) {
			return ;
		}
		LOCK_SCREEN->set_auto_count(false);
		if(water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT)){
			water::stop_timer_event(E_TIMER_EVENT_MAKE_WATER_TIMEOUT);
		}
		water::start_timer_event(E_TIMER_EVENT_DRAIN_WATER_SHORT);
	}else {
		water::stop_timer_event(E_TIMER_EVENT_DRAIN_WATER_SHORT);
		water::stop_timer_event(E_TIMER_EVENT_DRAIN_WATER_LONG);
		mDrainageWndPtr->setVisible(false);
		EASYUICONTEXT->hideNaviBar();
		LOCK_SCREEN->set_auto_count(true);
	}
}

static int isLackWater(int water_speed, bool lack_error) {
    // 返回值：
    // 0: 无缺水状态
    // 1: 常温冰水缺水
    // 2: 热水缺水

    static int64_t start;               // 记录开始时间（用于判断是否超过5秒）
    static bool is_first = true;        // 是否是第一次进入函数的标志
    int64_t now;                        // 当前时间
    static bool is_over_5s = false;     // 是否已经持续超过5秒的标志
    static int64_t start_over_5s;       // 记录超过5秒的时间点

    // 判断当前水的状态是否为常温冰水或普通水
    if (water::get_water_state() == E_WATER_STATE_ICE_WATER ||
        water::get_water_state() == E_WATER_STATE_COMMON_WATER) {

        // 如果是第一次进入该分支，记录当前时间并设置 is_first 为 false
        if (is_first) {
            start = base::uptime(); // 获取当前时间（单位：毫秒）
            is_first = false;
        } else {
            // 如果不是第一次，获取当前时间
            now = base::uptime(); // 获取当前时间（单位：毫秒）

            // 判断是否已经超过5秒，并且水流量小于230
            if ((now - start) / 1000 >= 5 && water_speed < 230) {
                // 如果还没有标记为超过5秒，则标记为 true，并记录超过5秒的时间点
                if (!is_over_5s) {
                    is_over_5s = true;
                    start_over_5s = now;
                } else {
                    // 如果已经标记为超过5秒，再判断是否持续了3秒
                    if ((now - start_over_5s) / 1000 >= 3) {
                        return 1; // 返回 1 表示常温冰水缺水
                    }
                }
            } else {
                // 如果条件不满足，重置 is_over_5s 标志
                is_over_5s = false;
            }
        }
    }
    // 判断当前水的状态是否为热水
    else if (water::get_water_state() == E_WATER_STATE_HOT_WATER) {
        static bool is_error = false; // 热水缺水错误的标志

        // 如果是第一次进入该分支，记录当前时间并设置 is_first 为 false
        if (is_first) {
            start = base::uptime();
            is_first = false;
        }

        // 如果之前没有缺水错误，并且当前检测到缺水错误
        if (!is_error && lack_error) {
            is_error = true; // 标记为缺水错误
            return 2;        // 返回 2 表示热水缺水
        }
        // 如果之前已经有缺水错误，并且当前仍然检测到缺水错误
        else if (is_error && lack_error) {
            now = base::uptime(); // 获取当前时间
            // 如果从开始时间到现在已经超过5秒
            if (now - start > 5000) {
                return 2; // 返回 2 表示热水缺水
            }
        }
        // 如果当前没有检测到缺水错误
        else if (!lack_error) {
            is_error = false; // 重置缺水错误标志
        }
    }
    // 如果当前水的状态既不是常温冰水/普通水，也不是热水
    else {
        // 重置首次进入标志
        is_first = true;
    }

    // 默认返回 0 表示无缺水状态
    return 0;
}

bool is_exist_warn(E_WARN_ID warn_id)
{
	switch(warn_id) {
		case E_WARN_ID_LACK_WATER_HOT:
			return 2 == isLackWater(Global::Water::water_speed, getProtocolData().inquiry_a5.warn_water_shortage_failure_error);
		case E_WARN_ID_LACK_WATER_OTHER:
			return 1 == isLackWater(Global::Water::water_speed, getProtocolData().inquiry_a5.warn_water_shortage_failure_error);
		case E_WARN_ID_INPUT_WATER_TEMP_SENSOR_ERROR:
			return getProtocolData().inquiry_a5.warn_input_water_temp_sensor_error == 1;
		case E_WARN_ID_INPUT_WATER_TEMP_LOW:
			return getProtocolData().inquiry_a5.warn_ice_detection == 1;
		case E_WARN_ID_OUTPUT_WATER_TEMP_SENSOR_ERROR:
			return getProtocolData().inquiry_a5.warn_output_water_temp_sensor_error == 1;
		case E_WARN_ID_VOLTAGE_SENSOR_ERROR:
			return getProtocolData().inquiry_a5.warn_voltage_sensor_error == 1;
		case E_WARN_ID_HEAT_FILM_ERROR:
			return getProtocolData().inquiry_a5.warn_heat_film_error == 1;
		case E_WARN_ID_OVER_TEMP:
			return getProtocolData().inquiry_a5.warn_over_temp == 1;
		case E_WARN_ID_ZERO_CIRCUIT_ERROR:
			return getProtocolData().inquiry_a5.warn_zero_circuit_error == 1;
		case E_WARN_ID_LEAK_ERROR:
			return getProtocolData().inquiry_e5_b2.leak_state == 1;
		case E_WARN_ID_COMMUNICATION_ERROR:
			return Global::Flags::bAutocheck;
		case E_WARN_ID_WATER_PUMP_OPEN:
			return getProtocolData().inquiry_a5.warn_water_pump_open == 1;
		default:
			return false;
	}
}


//设置对应故障信息
static void SetWarnWnd(int index) {
	if(Global::Flags::WarnIndex == index){	//如果警告窗口已经打开，则不再打开
		return;
	}
	LOGD("warn index: %d\n", index);
	Global::Flags::WarnIndex = index;
	if(index == 9) {
		protocol::closeAllValve();       //停止所有负载

		LOCK_SCREEN->screenOn();
		LOCK_SCREEN->set_auto_count(false);
		if(water::get_water_state() != E_WATER_STATE_IDLE) {
			stop_water(true);
		}
		water::stop_all_timer_event();
		//每10秒响一次
		static uint64_t last_time = 0;
	 	if(base::uptime() - last_time > 10000) {
		 	last_time = base::uptime();
		 	set_beep_count(3, 500);
	 	}
	}else{
		if(index == 2){
			protocol::closeAllValve();       //停止所有负载
			if(water::get_water_state() != E_WATER_STATE_IDLE) {
				stop_water(true);
			}
			water::stop_all_timer_event();
		}else{
			if(water::is_timer_event_running(E_TIMER_EVENT_ALL_BRASH))
				water::stop_timer_event(E_TIMER_EVENT_ALL_BRASH);

			if(water::is_timer_event_running(E_TIMER_EVENT_DRAIN_WATER_LONG))
			water::stop_timer_event(E_TIMER_EVENT_DRAIN_WATER_LONG);

			if(water::is_timer_event_running(E_TIMER_EVENT_DRAIN_WATER_SHORT))
			water::stop_timer_event(E_TIMER_EVENT_DRAIN_WATER_SHORT);
			if(index == 0){
				if(water::get_water_state() != E_WATER_STATE_IDLE) {
					stop_water(true);
				}
			}
			if(water::get_water_state() == E_WATER_STATE_HOT_WATER) {
				stop_water(true);
			}
		}
		if(Global::Other::beepVod == 0){
			Global::Other::beepVod = 1;
			set_beep_count(3, 500);
		}
	}

//  testbuf[index].state = 1;

//	mTipPtr->setPosition(warnTab[index].p);
//	mTip1Ptr->setText(warnTab[index].Warn1);
	mTipPtr->setText(warnTab[index].Warn);
	warnTab[index].IsShow = true;

	EASYUICONTEXT->showNaviBar();
	mWindowBgPtr->setVisible(true);

}

// 检查是否有 A5 相关的警告
static bool hasWarn(const SProtocolData &data) {
    if (data.cmd == INQUIRY_CMD_A5) {
        // 使用 std::map 存储 A5 相关的警告
        std::map<int, int> warnMap;
        warnMap[6] = data.inquiry_a5.warn_over_temp;
        warnMap[1] = data.inquiry_a5.warn_input_water_temp_sensor_error;
        warnMap[2] = data.inquiry_a5.warn_ice_detection;
        warnMap[3] = data.inquiry_a5.warn_output_water_temp_sensor_error;
        warnMap[4] = data.inquiry_a5.warn_voltage_sensor_error;
        warnMap[5] = data.inquiry_a5.warn_heat_film_error;
        warnMap[7] = data.inquiry_a5.warn_zero_circuit_error;
        warnMap[10] = data.inquiry_a5.warn_water_pump_open;

        // 遍历 map，检查是否有警告
        for (std::map<int, int>::const_iterator it = warnMap.begin(); it != warnMap.end(); ++it) {
            int warnIndex = it->first;  // 键 (警告索引)
            int warnStatus = it->second; // 值 (警告状态)

            if (warnStatus == 1) {
                SetWarnWnd(warnIndex);
                return true; // 找到一个警告就退出
            }
        }

        // 检查缺水警告
        if (isLackWater(Global::Water::water_speed, data.inquiry_a5.warn_water_shortage_failure_error)) {
            SetWarnWnd(0);
            return true;
        }
    }
    return false;
}

bool is_exit_warn_now(){
	if( is_exist_warn(E_WARN_ID_LACK_WATER_HOT) ||
		is_exist_warn(E_WARN_ID_LACK_WATER_OTHER) ||
		is_exist_warn(E_WARN_ID_INPUT_WATER_TEMP_SENSOR_ERROR) ||
		is_exist_warn(E_WARN_ID_INPUT_WATER_TEMP_LOW) ||
		is_exist_warn(E_WARN_ID_OUTPUT_WATER_TEMP_SENSOR_ERROR) ||
		is_exist_warn(E_WARN_ID_VOLTAGE_SENSOR_ERROR) ||
		is_exist_warn(E_WARN_ID_HEAT_FILM_ERROR) ||
		is_exist_warn(E_WARN_ID_OVER_TEMP) ||
		is_exist_warn(E_WARN_ID_ZERO_CIRCUIT_ERROR) ||
		is_exist_warn(E_WARN_ID_COMMUNICATION_ERROR) ||
		is_exist_warn(E_WARN_ID_LEAK_ERROR) ||
		is_exist_warn(E_WARN_ID_WATER_PUMP_OPEN)
		){
			return true;
		}
	return false;
}

// 检查一组定时器事件是否正在运行
bool areAnyTimersRunning(const std::vector<ETimerEventId>& timerIds) {
    for (ETimerEventId id : timerIds) {
        if (water::is_timer_event_running(id)) {
			set_timer_event_window_visible(id, true);
            return true;
        }
    }
    return false;
}

// 检查是否存在指定的警告 (并处理 WarnUI)
bool checkAndHandleWarns(const std::vector<E_WARN_ID>& warnIds) {
    for (E_WARN_ID id : warnIds) {
        if (is_exist_warn(id)) {
        	Global::Flags::WarnIndex = -1;
            return true;
        }
    }
    return false;
}

// 定义一个结构体来表示每个定时器事件的检查规则
struct TimerCheckRule {
    std::vector<ETimerEventId> conflictingTimers;  // 与当前操作冲突的定时器列表
    std::vector<E_WARN_ID> blockingWarns;         // 阻塞要执行操作的警告列表
};

bool is_can_start_auto_timer(E_TIMER_EVENT_ID id) {
    // 使用表驱动法来存储每个定时器事件的检查规则
    static const std::map<E_TIMER_EVENT_ID, TimerCheckRule> checkRules = {
        {E_TIMER_EVENT_ID_ICE_ADD_WATER, {
            { E_TIMER_EVENT_FILTER_BRASH,
            		E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},

            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},

        {E_TIMER_EVENT_ID_DRAIN_WATER_SHORT, {
            {
             E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_DRAIN_WATER_LONG, {
            {
             E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_ALL_BRASH, {
            {
             E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_FILTER_BRASH, {
            {
             E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_ICE_ADD_AND_DRAIN_WATER, {
            {
             E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_MAKE_WATER_TIMEOUT, {
            { },
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR}
        }},
        {E_TIMER_EVENT_ID_ZERO_STATE_WATER, {
            {}, // 没有冲突的定时器
            {E_WARN_ID_LEAK_ERROR}
        }},
        {E_TIMER_EVENT_ID_WATER_CHECK_PRESS_TEST, {
            {}, // 没有冲突的定时器
            {}  // 没有阻塞的警告
        }},
        {E_TIMER_EVENT_ID_WATER_OPERATE_HOT, {
            {E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH, E_TIMER_EVENT_DRAIN_WATER_SHORT,
            		E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LEAK_ERROR, E_WARN_ID_LACK_WATER_HOT, E_WARN_ID_INPUT_WATER_TEMP_SENSOR_ERROR, E_WARN_ID_INPUT_WATER_TEMP_LOW,
             E_WARN_ID_OUTPUT_WATER_TEMP_SENSOR_ERROR, E_WARN_ID_VOLTAGE_SENSOR_ERROR, E_WARN_ID_HEAT_FILM_ERROR,
             E_WARN_ID_OVER_TEMP, E_WARN_ID_ZERO_CIRCUIT_ERROR, E_WARN_ID_COMMUNICATION_ERROR, E_WARN_ID_WATER_PUMP_OPEN}
        }},
        {E_TIMER_EVENT_ID_WATER_OPERATE_OTHER, {
            {E_TIMER_EVENT_FILTER_BRASH, E_TIMER_EVENT_ALL_BRASH,
            		E_TIMER_EVENT_DRAIN_WATER_SHORT, E_TIMER_EVENT_DRAIN_WATER_LONG},
            {E_WARN_ID_LACK_WATER_OTHER, E_WARN_ID_INPUT_WATER_TEMP_LOW, E_WARN_ID_COMMUNICATION_ERROR, E_WARN_ID_LEAK_ERROR}
        }},
    };

    // 查找指定定时器事件的检查规则
    auto it = checkRules.find(id);
    if (it == checkRules.end()) {
        // 如果没有找到对应的规则，则默认允许启动 (或者根据你的需求返回 false)
        return true;
    }

    const TimerCheckRule& rule = it->second;

    // 检查是否有冲突的定时器正在运行
    if (areAnyTimersRunning(rule.conflictingTimers)) {
        return false;
    }

    // 检查是否存在阻塞的警告
    if (checkAndHandleWarns(rule.blockingWarns)) {
        return false;
    }

    return true;
}

void LvxinUi(){
	if(LOCK_SCREEN->getStatus() == E_LOCK_STATUS_UNLOCKED){
		if(((water::get_cartridge_life(E_CARTRIDGE_TYPE_PPC) == 0) ||
						(water::get_cartridge_life(E_CARTRIDGE_TYPE_C2) == 0) ||
						(water::get_cartridge_life(E_CARTRIDGE_TYPE_RO) == 0))){
			if(!Global::Flags::is_warn_cartridge_over){
				Global::Flags::is_warn_cartridge_over = true;
				EASYUICONTEXT->showNaviBar();
				mFilterOverWndPtr->setVisible(true);
				mFilterSoonWndPtr->setVisible(false);
			}

		}else if(((water::get_cartridge_life(E_CARTRIDGE_TYPE_PPC) <= 5 && water::get_cartridge_life(E_CARTRIDGE_TYPE_PPC) > 0) ||
				(water::get_cartridge_life(E_CARTRIDGE_TYPE_C2) <= 5 && water::get_cartridge_life(E_CARTRIDGE_TYPE_C2) > 0) ||
				(water::get_cartridge_life(E_CARTRIDGE_TYPE_RO) <= 5 && water::get_cartridge_life(E_CARTRIDGE_TYPE_RO) > 0))){

			if(!Global::Flags::is_warn_cartridge_dying){
				//			mWindow1Ptr->setVisible(true);
					//			mFilterOverWndPtr->setVisible(false);
				Global::Flags::is_warn_cartridge_dying = true;
						set_beep_count(3, 1000);
					//			EASYUICONTEXT->showNaviBar();
			}
		}
	}
}



static void WashTimeCount(int Washcount){
    char buf[100] = {0};
    snprintf(buf, sizeof(buf), "大约需要%d秒，请耐心等待", Washcount);
    mWashTipPtr->setText(buf);
}
//static void ShortTimeCount(int Washcount){
//    char buf[100] = {0};
//    snprintf(buf, sizeof(buf), "大约需要%d秒，请耐心等待", Washcount);
//    mTextView23Ptr->setText(buf);
//}
static void LongTimeCount(int Washcount){
    char buf[100] = {0};
    snprintf(buf, sizeof(buf), "大约需要%d秒，请耐心等待", Washcount);

}
static void WashLongTimeCount(int WashMin,int WashSecond){
    char buf[100] = {0};
    snprintf(buf, sizeof(buf), "大约需要%d分%d秒，请耐心等待", WashMin,WashSecond);
    mWashTipPtr->setText(buf);
}

// 该定时任务回调函数只用来处理 UI 相关的逻辑
static void _on_timer_event_cb_ui(int id, int run_time, int total_time, void *user_data) {
    if (id == E_TIMER_EVENT_ALL_BRASH) {
        //整机冲洗
        int remaining_time = total_time - run_time;  // 计算剩余时间
        int total_min = remaining_time / 60;         // 剩余分钟数
        int remaining_second = remaining_time % 60;  // 剩余秒数
        WashLongTimeCount(total_min, remaining_second);  // 更新长时间刷洗计时

        if (run_time == START_TIME_POINT) {
            // 开始时间点，显示刷洗窗口
            set_timer_event_window_visible(id, true);
        } else if (run_time == ALL_BASH1_TIME_POINT) {
            // 第一阶段完成（暂无操作）
        } else if (run_time == ALL_BASH2_TIME_POINT) {
            // 第二阶段完成（暂无操作）
        } else if (run_time == ALL_BASH3_TIME_POINT) {
            // 第三阶段完成（暂无操作）
        } else if (run_time == ALL_BASH4_TIME_POINT) {
            // 第四阶段完成，隐藏刷洗窗口
            set_timer_event_window_visible(id, false);
        }
    }
    else if (id == E_TIMER_EVENT_ICE_ADD_WATER) {
        // 冰水箱补水
    	if (run_time == ICE_ADD_WATER_TIME_POINT) {
            // 显示超时窗口，并重置锁计时
            set_timer_event_window_visible(id, true);
			}
    }
    else if (id == E_TIMER_EVENT_ICE_ADD_BLOCK) {
        // 制冰水箱补水
    	if (run_time == TIME_POINT_300) {
            // 显示超时窗口，并重置锁计时
            set_timer_event_window_visible(id, true);
			}
    }

    else if (id == E_TIMER_EVENT_MAKE_WATER_TIMEOUT) {
        // 制水事件
        Global::Water::waterTimeOut = run_time;  // 更新制水时间
        if (run_time == START_TIME_POINT) {
            // 开始时间点，暂无操作
        } else if (run_time == MAKE_WATER_TIMEOUT_TIME_POINT) {
            // 显示超时窗口，并重置锁计时
            set_timer_event_window_visible(id, true);
        }
    }
    else if (id == E_TIMER_EVENT_FILTER_BRASH) {
        // 滤芯刷洗事件
        WashTimeCount(total_time - run_time);  // 更新滤芯刷洗倒计时
        if (run_time == START_TIME_POINT) {
            // 开始时间点，显示刷洗窗口
            set_timer_event_window_visible(id, true);
        } else if (run_time == FILTER_BRASH_TIME_POINT) {
            // 刷洗完成，隐藏刷洗窗口
            set_timer_event_window_visible(id, false);
        }
    }
    else if (id == E_TIMER_EVENT_DRAIN_WATER_LONG) {
        // 长时间排水事件
        LongTimeCount(total_time - run_time);  // 更新长时间排水倒计时
        if (run_time == START_TIME_POINT) {
            // 开始时间点，显示排水窗口
            set_timer_event_window_visible(id, true);
        } else if (run_time == DRAIN_WATER_LONG_TIME_POINT) {
            // 排水完成，隐藏排水窗口
            set_timer_event_window_visible(id, false);
        }
    }
    else if (id == E_TIMER_EVENT_DRAIN_WATER_SHORT) {
        // 短时间排水事件
        // ShortTimeCount(total_time - run_time);  // 更新短时间排水倒计时（当前注释掉）

        if (run_time == START_TIME_POINT) {
            // 开始时间点，显示排水窗口
            set_timer_event_window_visible(id, true);
        } else if (run_time == DRAIN_WATER_SHORT_TIME_POINT) {
            // 排水完成，隐藏排水窗口
            set_timer_event_window_visible(id, false);
        }
    }
    else if (id == E_TIMER_EVENT_ZERO_STATE_WATER_A) {
        // 零陈水 A 事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_A1_TIME_POINT) {
            // 第一阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_A2_TIME_POINT) {
            // 第二阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_A3_TIME_POINT) {
            // 第三阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_A4_TIME_POINT) {
            // 第四阶段完成（暂无操作）
        }
    }
    else if (id == E_TIMER_EVENT_ZERO_STATE_WATER_B) {
        // 零陈水 B 事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_B1_TIME_POINT) {
            // 第一阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_B2_TIME_POINT) {
            // 第二阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_B3_TIME_POINT) {
            // 第三阶段完成（暂无操作）
        } else if (run_time == ZERO_STATE_WATER_B4_TIME_POINT) {
            // 第四阶段完成（暂无操作）
        }
    }

    else if (id == E_TIMER_EVENT_WATER_CHECK_PRESS_TEST) {
        // 水压检测测试事件
        if (run_time == START_TIME_POINT) {
            // 开始时间点（暂无操作）
        } else if (run_time == WATER_CHECK_PRESS_TEST_TIME_POINT) {
            // 测试完成（暂无操作）
        }
    }
}



static S_ACTIVITY_TIMEER REGISTER_ACTIVITY_TIMER_TAB[] = {
		{1,  500},
		{2,  1000},

};

/**
 * 当界面构造时触发
 */
static void onUI_init(){
	//初始化定时任务回调
	water::add_timer_event_ui(_on_timer_event_cb_ui);
	LvxinUi();
}

/*
 * 当界面完全退出时触发
 */
static void onUI_quit() {
	water::remove_timer_event_ui(_on_timer_event_cb_ui);
}


// 处理 E5B2 命令的函数
static void handleE5B2Command(const SProtocolData &data) {
    // 净水箱水位到达高水位即可制水
    if (data.inquiry_e5_b2.clear_water_high_level == 1) {
        // 如果零陈水A定时器事件正在运行，则停止该事件
        if (water::is_timer_event_running(E_TIMER_EVENT_ZERO_STATE_WATER_A)) {
            water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
        }

        // 如果超时窗口未显示
        if (!mOutTimeWndPtr->isWndShow()) {
            // 如果 "制水" 和 "冰水加水排水" 定时器事件均未运行
            if (!water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT) ) {

                // 检查是否可以启动 "制水" 定时器事件
                if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_MAKE_WATER_TIMEOUT)) {
                    // 如果无法启动，则不执行任何操作
                } else {
                    // 否则启动 "制水" 定时器事件
                    water::start_timer_event(E_TIMER_EVENT_MAKE_WATER_TIMEOUT);
                }
            }
            // 如果 "制水" 和 "冰水加水排水" 定时器事件都在运行
            else if (water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT) ) {
                // 停止 "制水" 定时器事件
                water::stop_timer_event(E_TIMER_EVENT_MAKE_WATER_TIMEOUT);
            }
        }
        // 超时
        else {
            if (water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT)) {
                water::stop_timer_event(E_TIMER_EVENT_MAKE_WATER_TIMEOUT);
            }
        }
    }
    // 低水位即可停止制水
    else {
        // 如果 "制水" 定时器事件正在运行
        if (water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT)) {
            // 停止 "制水" 定时器事件
            water::stop_timer_event(E_TIMER_EVENT_MAKE_WATER_TIMEOUT);
            // 启动零陈水A定时器事件
            water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
            //没有制冰且不是排空状态
            if(!isIceOpen() && data.inquiry_a2.DrainBoxPumpAD > 210){
            	getProtocolParam().control_aa_a1.CmdDrainBoxPump = true;		//打开“接水盒排水泵”负载
            }
        }
    }

    // 如果设备当前状态不为空闲（即设备正在工作）
    if (water::get_water_state() != E_WATER_STATE_IDLE) {
        // 刷新 TDS 数据（包括 tds1、tds2 和输入水温）
        water::refresh_TDS_data(data.inquiry_e5_b2.tds1_value, data.inquiry_e5_b2.tds2_value, data.inquiry_a5.input_water_temp);

        // 静态变量，用于记录上一次刷新的时间
        static int64_t mLastTime = 0;
        // 获取当前时间戳
        int64_t curTime = base::uptime();

        // 如果距离上次刷新的时间间隔大于等于 TDS_SWITCH_TIME
        if (curTime - mLastTime >= TDS_SWITCH_TIME) {
            mLastTime = curTime;  // 更新时间戳
            protocol::setTds(true, false);  // 开启 TDS 功能
        } else {
            protocol::setTds(false, false);  // 关闭 TDS 功能
        }

    }
}

class IceOnThread: public Thread {
 public:
   virtual bool threadLoop() {

     if(Global::Timer::compressorTime > COMPRESSORTIME )
     {
    	 if(isIceOpen())
    	 {
        	 water::set_task_load(E_TASK_ID_MAKE_ICE, true, {	E_DEV_LOAD_TYPE_COMPRESSOR, E_DEV_LOAD_TYPE_INTAKE_FAN, E_DEV_LOAD_TYPE_CONDENSER_FAN,});
             water::start_timer_event(E_TIMER_EVENT_MAKE_ICEPUMP);
    	 }
    	return false;
     }else if(exitPending()) {
         return false;
     }
     sleep(1000);

     return true;
   }
};
static IceOnThread iceOn;

static void handleA2Command(){

	if(Cur_a2.IceMakingWaterLevel )
	{
//		LOGD("制冰水箱”水位标志位 完成补水");
        if (water::is_timer_event_running(E_TIMER_EVENT_ICE_ADD_BLOCK)) {
            water::stop_timer_event(E_TIMER_EVENT_ICE_ADD_BLOCK);
        }
		if(Global::Flags::internalCleaning)
		{
			if(Global::Flags::start_ice){
	            if (!water::is_timer_event_running(E_TIMER_EVENT_INTER_CLEAN)) {
	            		water::start_timer_event(E_TIMER_EVENT_INTER_CLEAN, TIME_POINT_300);
	            		Global::Flags::start_ice = false;
	            }
			}
		}
		else if(isIceOpen())
		{
	        if(Global::Flags::start_ice)
	        {
	            //开启制冰
	            if (isCompressor() || Global::Timer::compressorTime > COMPRESSORTIME) {
	            	water::set_task_load(E_TASK_ID_MAKE_ICE, true, {	E_DEV_LOAD_TYPE_COMPRESSOR, E_DEV_LOAD_TYPE_INTAKE_FAN, E_DEV_LOAD_TYPE_CONDENSER_FAN,});
	                water::start_timer_event(E_TIMER_EVENT_MAKE_ICEPUMP);
	            }else{
	            	iceOn.run();
	            }
	            Global::Flags::start_ice =false;
	        }
	        if(Cur_a2.IceMakingWaterNTCTemp <= 1 && !water::is_timer_event_running(E_TIMER_EVENT_MAKE_ICEPUMP) ){
	        	if(getProtocolParam().control_aa_a1.CmdIceMakingPump){
	        		water::start_timer_event(E_TIMER_EVENT_MAKE_ALLICE, Global::Timer::singleice);
	        	}
	        }
		}else{
			if(iceOn.isRunning())iceOn.requestExit();
		}

	}
}

static void secProtocal(){
	static uint8_t secTank = 0;
	static uint8_t secTankH = 0;
	//冰水箱浮球开关处于低水位后
	if(!Cur_a2.ColdWaterTankLowLevel && !Cur_a2.ColdWaterTankHighLevel){
		secTank++;
		if(secTank > 2){
	        // 如果超时窗口未显示
	        if (!mOutTimeWndPtr->isWndShow()) {
	            // 如果 补水事件未运行
	            if (!water::is_timer_event_running(E_TIMER_EVENT_ICE_ADD_WATER) ) {

	                // 检查是否可以启动 "补水" 定时器事件
	                if (!is_can_start_auto_timer(E_TIMER_EVENT_ID_ICE_ADD_WATER)) {
	                    // 如果无法启动，则不执行任何操作
	                } else {
	                    water::start_timer_event(E_TIMER_EVENT_ICE_ADD_WATER);
	                }
	            }

	        }
	        // 超时
	        else {
	            if (water::is_timer_event_running(E_TIMER_EVENT_ICE_ADD_WATER)) {
	                water::stop_timer_event(E_TIMER_EVENT_ICE_ADD_WATER);
	            }
	        }
		}
    }else{
    	secTank = 0;
    }
    // 水位浮球状态处于高水位状态时
    if(Cur_a2.ColdWaterTankHighLevel){
    	secTankH++;
		if(secTankH > 2){
	        if (water::is_timer_event_running(E_TIMER_EVENT_ICE_ADD_WATER)) {
	            water::stop_timer_event(E_TIMER_EVENT_ICE_ADD_WATER);
	        }
		}
    }else{
    	secTankH = 0;
    }

	static uint8_t DrainTime = 0;
    //处于排空状态
    if(getProtocolParam().control_aa_a1.CmdDrainBoxPump && Cur_a2.DrainBoxPumpAD < 200){
    	DrainTime++;
    	if(DrainTime > 2){
    		if(Global::Flags::internalCleaning){
    			internalClean(false);
    		}
    		else if(Global::Flags::Auto_iceing)
    		{
    			getProtocolParam().control_aa_a1.CmdDrainBoxPump = false;		//关闭“接水盒排水泵”负载
    		}
    	}
    }else{
    	DrainTime = 0;
    }
}


static void handleProtocolCommand(const SProtocolData &data) {
    switch (data.cmd) {
        case INQUIRY_CMD_A5:
            // (TODO: A5命令的处理逻辑)
            break;
        case INQUIRY_CMD_E5_B1:
            // (TODO: E5_B1命令的处理逻辑)
            break;
        case INQUIRY_CMD_E5_B2:
            handleE5B2Command(data); // 提取 E5_B2 命令的处理
            break;
        case INQUIRY_CMD_E5_E1:
            // (TODO: E5_E1命令的处理逻辑)
            break;
    }
	if(Cur_a2.RespPushRodMotorForward && Cur_a2.DetectionMicroSwitch){
		if(Global::Flags::forceDefrost)
		{
	        if (!water::is_timer_event_running(E_TIMER_EVENT_FORCE_OUT)) {
	            water::start_timer_event(E_TIMER_EVENT_FORCE_OUT, TIME_POINT_600);
	        }
		}
		else
		{
			if(isIceOpen() && !water::is_timer_event_running(E_TIMER_EVENT_ROD_MOTOR)){
				water::start_timer_event(E_TIMER_EVENT_ROD_MOTOR);
			}
		}
	}
}

/**
 * 串口数据回调接口
 */
static void onProtocolDataUpdate(const SProtocolData &data) {
    //串口数据回调接口
	Global::Flags::LackOfWater = data.inquiry_a5.warn_water_shortage_failure_error;
	if(Global::Flags::is_init_ui ){
		Global::Flags::Serial_flag = true;
		// 使用 hasWarn 函数来处理警告
		if (!hasWarn(data)) {
			// 如果没有 A5 相关的警告，则继续检查其他命令
			if (data.cmd == INQUIRY_CMD_E5_B2) {
				if (data.inquiry_e5_b2.leak_state == 1) {
					SetWarnWnd(9); // 漏水警告
				}
			} else if (data.cmd == INQUIRY_CMD_E5_E1) {
				// E5_E1 的处理 (如果需要)
			}
		}
		std::memcpy(&Cur_a2, &data.inquiry_a2, sizeof(Inquiry_A2));
        // 根据 data.cmd 处理不同的协议命令
        handleProtocolCommand(data);
	}

}


/**
 * 定时器触发函数
 * 不建议在此函数中写耗时操作，否则将影响UI刷新
 * 参数： id
 *         当前所触发定时器的id，与注册时的id相同
 * 返回值: true
 *             继续运行当前定时器
 *         false
 *             停止运行当前定时器
 */
static bool onUI_Timer(int id){
	switch (id) {
	case 1:{
			LvxinUi();
			if(!is_exit_warn_now()){
				if(Global::Flags::WarnIndex != -1) {
					Global::Flags::WarnIndex = -1;
				}
			}
	}break;
	case 2:{
		secProtocal();
	    handleA2Command();
	}break;
		default:
			break;
	}
    return true;
}

/**
 * 有新的触摸事件时触发
 * 参数：ev
 *         新的触摸事件
 * 返回值：true
 *            表示该触摸事件在此被拦截，系统不再将此触摸事件传递到控件上
 *         false
 *            触摸事件将继续传递到控件上
 */
static bool onnavibarActivityTouchEvent(const MotionEvent &ev) {
    switch (ev.mActionStatus) {
		case MotionEvent::E_ACTION_DOWN://触摸按下
			//LOGD("时刻 = %ld 坐标  x = %d, y = %d", ev.mEventTime, ev.mX, ev.mY);
			break;
		case MotionEvent::E_ACTION_MOVE://触摸滑动
			break;
		case MotionEvent::E_ACTION_UP:  //触摸抬起
			break;
		default:
			break;
	}
	return false;
}

static bool onButtonClick_Button_brash_cancel(ZKButton *pButton) {
    LOGD(" ButtonClick Button_brash_cancel !!!\n");
    operateBrash(false);
    return false;
}

//显示制冷提示窗口
void showRefrigerWnd(){
	if(isColdOpen()){
		mrefrigerTipPtr->setText("是否关闭制冷");
	}else{
		mrefrigerTipPtr->setText("是否开启制冷");
	}
	EASYUICONTEXT->showNaviBar();
	mrefrigerationWndPtr->showWnd();
}
static bool onButtonClick_refrigerationOn(ZKButton *pButton) {
    LOGD(" ButtonClick refrigerationOn !!!\n");
	operateCold(!isColdOpen());
	mrefrigerationWndPtr->hideWnd();

    return false;
}

static bool onButtonClick_Hide2(ZKButton *pButton) {
    LOGD(" ButtonClick Hide2 !!!\n");
    mrefrigerationWndPtr->hideWnd();
    EASYUICONTEXT->hideNaviBar();
    return false;
}

static bool onButtonClick_Cancel_Hydrate(ZKButton *pButton) {
    LOGD(" ButtonClick Cancel_Hydrate !!!\n");
    water::stop_timer_event(E_TIMER_EVENT_ICE_ADD_WATER);

	 water::stop_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);
	 water::start_timer_event(E_TIMER_EVENT_ZERO_STATE_WATER_A);

	EASYUICONTEXT->hideNaviBar();
//	mWindowBgPtr->setVisible(true);
    mHydrateTipWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_Hide1(ZKButton *pButton) {
    LOGD(" ButtonClick Hide1 !!!\n");

    mHydrateTipWndPtr->setVisible(false);
    return false;
}


static bool onButtonClick_Cancel_Drainage2(ZKButton *pButton) {
    LOGD(" ButtonClick Cancel_Drainage2 !!!\n");

	EASYUICONTEXT->hideNaviBar();
//	mWindowBgPtr->setVisible(true);
    mDrainageTipWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_HIde5(ZKButton *pButton) {
    LOGD(" ButtonClick HIde5 !!!\n");

    mDrainageTipWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_DrainageQuit(ZKButton *pButton) {
    LOGD(" ButtonClick DrainageQuit !!!\n");
    operateEmptyDevice(false);
    return false;
}

static bool onButtonClick_expiredok(ZKButton *pButton) {
    LOGD(" ButtonClick expiredok !!!\n");
    Global::Flags::is_open_warn_cartridge_over = false;
    EASYUICONTEXT->hideNaviBar();
    mFilterOverWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_skip(ZKButton *pButton) {
    LOGD(" ButtonClick skip !!!\n");
    EASYUICONTEXT->hideNaviBar();
    mFilterOverWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_HIde6(ZKButton *pButton) {
    LOGD(" ButtonClick HIde6 !!!\n");
    return false;
}

static bool onButtonClick_OK(ZKButton *pButton) {
    LOGD(" ButtonClick OK !!!\n");
    Global::Other::beepVod = 0;
    LOCK_SCREEN->set_auto_count(true);
	mWindowBgPtr->setVisible(false);
    EASYUICONTEXT->hideNaviBar();
    return false;
}
static bool onButtonClick_Button1(ZKButton *pButton) {
    LOGD(" ButtonClick Button1 !!!\n");
    mOutTimeWndPtr->hideWnd();
    EASYUICONTEXT->hideNaviBar();
    return false;
}
static bool onButtonClick_Button2(ZKButton *pButton) {
    LOGD(" ButtonClick Button2 !!!\n");
    mTimeIceWndPtr->hideWnd();
    EASYUICONTEXT->hideNaviBar();
    water::start_timer_event(E_TIMER_EVENT_ICE_ADD_BLOCK);
    return false;
}
static bool onButtonClick_Button3(ZKButton *pButton) {
    LOGD(" ButtonClick Button3 !!!\n");
    mTimeIceWaterWndPtr->hideWnd();
    EASYUICONTEXT->hideNaviBar();
    water::start_timer_event(E_TIMER_EVENT_ICE_ADD_WATER);
    return false;
}
